import {reqCartList,reqDeleteCart,reqSelected} from '@/api';

const actions ={
    async getCartList({commit}){
        let result =  await reqCartList();
        if(result.code==200){
            commit('GETCARTLIST',result.data)
        }
    },
    async deleteCart(context,value){
        let result = await reqDeleteCart(value);
        if(result.code==200) return '删除成功';
        else return Promise.reject(new Error('删除失败'))
    },
    async cartSelected(context,{skuId,isChecked}){
        let result = await reqSelected(skuId,String(isChecked));
        if(result.code==200) return '修改勾选成功';
        else return Promise.reject(new Error(''))
    },
    async cartAllSelected({dispatch,state},isChecked){
        let promiseAll=[]
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('cartSelected',{skuId:item.skuId,isChecked})
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll);
    }

};

const mutations ={
    GETCARTLIST(state,cartList){
        state.cartList=cartList;
    }

};

const state ={
    cartList:[]
    
};


const getters ={
    cartList(state){
        return state.cartList[0] || {}
    },
};

export default {
    namespaced:true,
    state,
    mutations,
    actions,
    getters
}